/**
 * 用户日历备忘录
 * @author williamJM
 * date 2018/04/17 19:45
 */

"use strict";

define(['app',"config/pathConfig","moment","layer","blockui"],function(app,pathConfig,moment){
    app.registerController('ctrl.calendar',function($rootScope,$scope,$http,initUIComponent){

        $scope.eventTitle = "";
        initUIComponent.init();

        //获取用户事件标签
        var getEventLabelData = function () {
            return new Promise(function (success,error) {
                $http.get(pathConfig.backstagePath.getPath() + "/user/eventLabel")
                    .then(function successCallback(response) {
                        //$rootScope.resultHandler(response.data.status);
                       success(response.data.data);
                    });
            });
        };

        var initDrag = function (el) {
            var eventObject = {
                title: $.trim(el.text())
            };
            el.data('eventObject', eventObject);
            el.draggable({
                zIndex: 999,
                revert: true,
                revertDuration: 0
            });
        };


        var init = function () {
            getEventLabelData().then(function (response) {
                if(response !== null && response.length > 0) {
                    for(var i = 0; i < response.length;i++) {
                        $(".event-label").append("<div data-labelId='"+response[i].labelId+"' class='external-event label'>"+response[i].name+"</div>");
                    }
                    $('#external-events div.external-event').each(function () {
                        initDrag($(this))
                    });
                }
            });
        };
        init();


        //boolean转数字
        var booleanToInt = function(b) {
            return b === true ? 1 : 0;
        };


        //创建新事件
        var createEvent = function (event) {
            return new Promise(function (success,error) {
                $http.post(pathConfig.backstagePath.getPath() + "/user/event",event)
                    .then(function successCallback(response) {
                        success(response);
                    })
            })
        };

        //删除日历标签
        var deleteLabelId = function (labelId) {
            return new Promise(function (success) {
                $http.delete(pathConfig.backstagePath.getPath() + "/user/eventLabel/" + labelId)
                    .then(function (response) {
                        success(response.data);
                    })
            })
        };


        //配置日历参数
        $('#calendar').fullCalendar({
                header : {
                    left: 'title',
                    right: 'prev,next,today,month,agendaWeek,agendaDay'
                },
                slotMinutes: 15,
                editable: true,
                droppable: true,
                columnFormat : {
                    month: 'dddd',
                    week: 'M月d日 ddd',
                    day: 'M月d日 dddd'
                },
                titleFormat : "yyyy年MM月",
                buttonText : {
                    today: '今天',
                    month: '月',
                    week: '周',
                    day: '天'
                },
                monthNames : ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月',
                    '十月', '十一月', '十二月'],
                dayNames : ['星期日', '星期一', '星期二', '星期三',
                    '星期四', '星期五', '星期六'],
                dayNamesShort : ['周日', '周一', '周二', '周三', '周四', '周五', '周六'],

                //拖动事件时的不透明度
                dragOpacity : 0.7,
                drop: function (date, allDay,e) {
                    var $this = $(this);
                    createEvent({
                        labelId : $(e.target).attr("data-labelId"),
                        start : date,
                        end : date,
                        isAllDay : booleanToInt(allDay)
                    }).then(function (response) {
                        if(response.data.status === 200) {
                            var originalEventObject = $this.data('eventObject');
                            var copiedEventObject = $.extend({}, originalEventObject);
                            copiedEventObject.start = date;
                            copiedEventObject.end = date;
                            copiedEventObject.allDay = allDay;
                            copiedEventObject.className = $(this).attr("data-class");
                            $('#calendar').fullCalendar('renderEvent', copiedEventObject, true);
                            if ($('#drop-remove').is(':checked')) {
                                $this.remove();
                                deleteLabelId($this.attr("data-labelId"));
                            }
                        }
                    });
                },
                eventDrop : function (event, dayDelta, minuteDelta, allDay) {
                    updateEvent({
                        labelId : event.labelId,
                        eventId : event.id,
                        start : event.start,
                        end : event.end,
                        isAllDay : booleanToInt(allDay)
                    });
                },
                eventResize : function (event, dayDelta, minuteDelta, allDay) {
                    updateEvent({
                        labelId : event.labelId,
                        eventId : event.id,
                        start : event.start,
                        end : event.end,
                        isAllDay : booleanToInt(allDay)
                    });
                },
            events : function () {
                $("#calendar").fullCalendar('removeEvents');
                $http.get(pathConfig.backstagePath.getPath() + "/user/event")
                    .then(function successCallback(response) {
                        var data = response.data.data;
                        for(var i = 0; i < data.length; i++) {
                            var obj = {
                                id : data[i].eventId,
                                title : data[i].userEventLabel.name,
                                start : new Date(data[i].start),
                                end : new Date(data[i].end),
                                allDay : isAllDay(data[i].isAllDay),
                                labelId : data[i].labelId
                            };
                            $('#calendar').fullCalendar('renderEvent', obj, true);
                        }
                    });
            }
        });


        //更新用户事件
        var updateEvent = function (event) {
          $http.put(pathConfig.backstagePath.getPath() + "/user/event",event)
              .then(function successCallback(response) {
              },function errorCallback(res) {
              });
        };

        var initDrag = function (el) {
            var eventObject = {
                title: $.trim(el.text())
            };
            el.data('eventObject', eventObject);
            el.draggable({
                zIndex: 999,
                revert: true,
                revertDuration: 0
            });
        };


        //向数据库中添加事件标签
        var submit = function (data) {
            return new Promise(function (success,error) {
                $http.post(pathConfig.backstagePath.getPath() + "/user/eventLabel",{name:data})
                    .then(function successCallback(response) {
                       success(response);
                    })
            });
        };

        //添加事件标签
        $scope.addEventLabel = function () {
            if($scope.eventTitle.length > 0) {
                submit($scope.eventTitle).then(function (response) {
                    if(response.data.status === 200) {
                        var html = $("<div data-labelId="+response.data.data+" class='external-event label'>" + $scope.eventTitle + "</div>");
                        $(".event-label").append(html);
                        initDrag(html);
                    }
                });
            }
        };

        //判断是否是全天事件
        var isAllDay = function (data) {
            return data !== 0;
        };


    });
});
